using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Ideopuzzle
{
    public class VirtualKeyboard
    {
        #region Fields

        SpriteBatch sprite_batch;
        TextEdit text_edit;
        List<MenuEntry> entries;
        List<RenderableObject> renderables;

        #endregion

        #region Constructors

        public VirtualKeyboard(SpriteBatch sprite_batch, SpriteFont font, TextEdit text_edit, Texture2D key_box, 
            string[] keys_label, int key_width, int key_height, int x_coord, int y_coord, 
            int x_spacing, int y_spacing, int rows_n)
        {
            this.sprite_batch = sprite_batch;
            this.text_edit = text_edit;

            entries = new List<MenuEntry>();
            renderables = new List<RenderableObject>();

            int colums = keys_label.Length / rows_n + keys_label.Length % rows_n;

            for (int i = 0; i < rows_n; i++)
            {
                for (int j = 0; j < colums - keys_label.Length % (i + 1); j++)
                {
                    BoxedLabelButton b = new BoxedLabelButton(sprite_batch, key_box,
                        new Vector2(x_coord + (key_box.Width + x_spacing) * j, y_coord + (key_box.Height + y_spacing) * i),
                        font, keys_label[i * colums + j], Color.White);

                    b.OnPress += new Press((MenuEntry m) => { text_edit.AddChar(b.Label); });

                    entries.Add(b);
                }
            }
        }

        #endregion

        #region Draw Methods

        public void DrawInsideSpriteBatch(GameTime gameTime)
        {
            for (int i = 0; i < renderables.Count; i++)
            {
                renderables[i].DrawAfterBegin();
            }

            for (int i = 0; i < entries.Count; i++)
            {
                entries[i].DrawInsideSpriteBatch();
            }

            text_edit.DrawInsideSpriteBatch(gameTime);
        }

        public void DrawOutsideSpriteBatch(GameTime gameTime)
        {
            sprite_batch.Begin();

            DrawInsideSpriteBatch(gameTime);

            sprite_batch.End();
        }

        #endregion

        #region Proprieties

        public TextEdit TextEdit { get { return text_edit; } }

        #endregion
    }
}
